package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.EmpArea;
import com.ruoyi.system.domain.EmpNormCollect;
import com.ruoyi.system.domain.EmpNormSystem;
import com.ruoyi.system.mapper.EmpNormCollectMapper;
import com.ruoyi.system.service.IEmpAreaService;
import com.ruoyi.system.service.IEmpNormCollectService;
import com.ruoyi.system.service.IEmpNormSystemService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 指标采集Service业务层处理
 *
 * @author zsl
 * @date 2024-04-15
 */
@Service
@Slf4j
public class EmpNormCollectServiceImpl extends ServiceImpl<EmpNormCollectMapper, EmpNormCollect> implements IEmpNormCollectService {

    @Autowired
    private IEmpNormSystemService iEmpNormSystemService;
    @Autowired
    private IEmpAreaService iEmpAreaService;

    /**
     * 查询指标采集
     *
     * @param id 指标采集主键
     * @return 指标采集
     */
    @Override
    public EmpNormCollect selectEmpNormCollectById(Long id) {
        return this.baseMapper.selectEmpNormCollectById(id);
    }

    /**
     * 查询指标采集列表
     *
     * @param empNormCollect 指标采集
     * @return 指标采集
     */
    @Override
    public List<EmpNormCollect> selectEmpNormCollectList(EmpNormCollect empNormCollect) {
        List<EmpNormCollect> empNormCollects = this.baseMapper.selectEmpNormCollectList(empNormCollect);

        empNormCollects.forEach(collect -> {
            EmpNormSystem empNormSystem = iEmpNormSystemService.selectEmpNormSystemById(collect.getSystemId());
            if (ObjectUtils.isNotEmpty(empNormSystem)) {
                collect.setEmpNormSystem(empNormSystem);
            }
            EmpArea empArea = iEmpAreaService.selectEmpAreaById(collect.getAreaId());
            if (ObjectUtils.isNotEmpty(empArea)) {
                collect.setEmpArea(empArea);
            }
        });

        return empNormCollects;
    }

    /**
     * 新增指标采集
     *
     * @param empNormCollect 指标采集
     * @return 结果
     */
    @Override
    public int insertEmpNormCollect(EmpNormCollect empNormCollect) {
        empNormCollect.setCreateTime(DateUtils.getNowDate());
        return this.baseMapper.insertEmpNormCollect(empNormCollect);
    }

    /**
     * 修改指标采集
     *
     * @param empNormCollect 指标采集
     * @return 结果
     */
    @Override
    public int updateEmpNormCollect(EmpNormCollect empNormCollect) {
        empNormCollect.setUpdateTime(DateUtils.getNowDate());
        return this.baseMapper.updateEmpNormCollect(empNormCollect);
    }

    /**
     * 批量删除指标采集
     *
     * @param ids 需要删除的指标采集主键
     * @return 结果
     */
    @Override
    public int deleteEmpNormCollectByIds(Long[] ids) {
        return this.baseMapper.deleteEmpNormCollectByIds(ids);
    }

    /**
     * 删除指标采集信息
     *
     * @param id 指标采集主键
     * @return 结果
     */
    @Override
    public int deleteEmpNormCollectById(Long id) {
        return this.baseMapper.deleteEmpNormCollectById(id);
    }

    @Override
    public String importEmpNormCollect(List<EmpNormCollect> collectList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(collectList) || collectList.isEmpty()) {
            return "导入指标采集数据不能为空";
        }
        AtomicInteger successNum = new AtomicInteger(0);
        AtomicInteger failureNum = new AtomicInteger(0);
        int count = 0;
        StringBuilder failureMsg = new StringBuilder();
        Date nowDate = DateUtils.getNowDate();
        try {
            for (EmpNormCollect collect : collectList) {
                count++;
                //赋值指标体系ID
                String attributeName = collect.getAttributeName();
                //赋值采集区域ID
                String areaName = collect.getAreaName();
                if (StringUtils.isAnyBlank(attributeName, areaName, collect.getYear())) {
                    failureNum.getAndIncrement();
                    failureMsg.append("<br/>").append("第 ").append(count).append(" 条数据，").append("指标属性名称或采集区域名称或采集时间不能为空，请检查后重新导入");
                    continue;
                }
                List<EmpNormSystem> empNormSystems = iEmpNormSystemService.list(Wrappers.lambdaQuery(EmpNormSystem.class).eq(EmpNormSystem::getName, attributeName));
                if (ObjectUtils.isEmpty(empNormSystems)) {
                    failureNum.getAndIncrement();
                    failureMsg.append("<br/>").append("第 ").append(count).append(" 条数据，").append("体系模块中-指标属性名称不存在，请检查后重新导入");
                    continue;
                }
                List<EmpArea> empAreas = iEmpAreaService.list(Wrappers.lambdaQuery(EmpArea.class).eq(StringUtils.isNumeric(areaName), EmpArea::getCode, areaName).eq(!StringUtils.isNumeric(areaName), EmpArea::getName, areaName));
                if (ObjectUtils.isEmpty(empAreas)) {
                    failureNum.getAndIncrement();
                    failureMsg.append("<br/>").append("第 ").append(count).append(" 条数据，").append("采集区域名称不存在，请检查后重新导入");
                    continue;
                }
                collect.setSystemId(empNormSystems.get(0).getId());
                collect.setAreaId(empAreas.get(0).getId());

                if (ObjectUtils.isEmpty(collect.getId())) {
                    //新增
                    collect.setCreateBy(operName);
                    collect.setCreateTime(nowDate);
                } else {
                    EmpNormCollect byId = this.getById(collect.getId());
                    if (ObjectUtils.isNotEmpty(byId)) {
                        //更新
                        collect.setUpdateBy(operName);
                        collect.setUpdateTime(nowDate);
                    } else {
                        //新增
                        collect.setCreateBy(operName);
                        collect.setCreateTime(nowDate);
                    }
                }
                successNum.getAndIncrement();
            }

            //数据校验
            List<EmpNormCollect> normCollects = collectList.stream().filter(collect -> ObjectUtils.allNotNull(collect.getSystemId(), collect.getAreaId()) && StringUtils.isNotEmpty(collect.getYear())).collect(Collectors.toList());

            if (isUpdateSupport) {
                this.saveOrUpdateBatch(normCollects);
            } else {
                //批量新增
                normCollects = normCollects.stream().filter(col -> ObjectUtils.isNotEmpty(col.getCreateTime())).collect(Collectors.toList());
                this.saveBatch(normCollects);
            }
        } catch (Exception e) {
            log.error("批量导入指标采集数据异常：", e);
        }
        String resultMsg = "导入完成，总数量：" + collectList.size() + "，成功数量：" + successNum + "，失败数量：" + failureNum;
        if (StringUtils.isNotEmpty(failureMsg.toString())) {
            resultMsg = resultMsg + "<br/>错误原因如下：<br/>" + failureMsg;
        }
        return resultMsg;
    }
}
